package com.xyebank.ledger.conf;

import com.xyebank.framework.core.utils.ApplicationContextAware;
import com.xyebank.ledger.anon.MigTaskComponent;
import com.xyebank.ledger.service.common.MigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.autoconfigure.AutoConfigureAfter;
//import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Proxy;
import java.util.Map;

@Configuration
//@AutoConfigureAfter({SpringContextAware.class})
public class MigTaskScan {
    private Logger logger	= LoggerFactory.getLogger(getClass());

    @Autowired
    ApplicationContextAware applicationContextAware;

    /**
     * 非常重要的扫描器
     * @return
     */
    @Bean
    public MigTaskBean scan() {
        MigTaskBean bean = new MigTaskBean();

        //扫描带有注解的包　放到bean中去
        logger.info("进入迁移任务扫描器");
        ApplicationContext context = applicationContextAware.getApplicationContext();
        logger.info("获取context");
        Map<String, Object> serviceBeanMap = context.getBeansWithAnnotation(MigTaskComponent.class);
        logger.info("准备一个个的解析并注入");
        for (Object serviceBean : serviceBeanMap.values()) {
            try {
                //获取自定义注解上的value
                String type;
                if(serviceBean instanceof Proxy) {
                    type = AopUtils.getTargetClass(serviceBean).getAnnotation(MigTaskComponent.class).type();
                } else {
                    type = serviceBean.getClass().getAnnotation(MigTaskComponent.class).type();
                }

                System.out.println("发现迁移任务:" + type);
                bean.addTask(type, (MigService) serviceBean);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return bean;
    }
}
